//
//  CacheDataHelper.m
//  CacheDemo
//
//  Created by liuyonghu on 2019/2/26.
//  Copyright © 2019年 liuyonghu. All rights reserved.
//

#define SPACETIME  150

#import "CacheDataHelper.h"
@interface CacheDataHelper()
@property(nonatomic,strong) NSCache *cacheTool;
@property(nonatomic,strong)NSMutableArray *keyList;
@end
@implementation CacheDataHelper
+ (CacheDataHelper *)shareHelper {
    
    static CacheDataHelper *helper = nil;
    static dispatch_once_t onceToken;
    if(helper == nil){
        dispatch_once(&onceToken, ^{
            
            helper = [[CacheDataHelper alloc]init];
            helper.cacheTool = [[NSCache alloc]init];
            helper.keyList = [NSMutableArray array];
            helper.timer = [NSTimer timerWithTimeInterval:SPACETIME repeats:YES block:^(NSTimer * _Nonnull timer) {
                [helper checkData];
            }];
            NSRunLoop *runloop=[NSRunLoop currentRunLoop];
            [runloop addTimer:helper.timer forMode:NSDefaultRunLoopMode];
            [helper.timer fire];
        });
    }
    
    return helper;
}

- (void)saveCacheData: (id)data byKey:(NSString *)key{
      NSDictionary *tempData = @{@"time":@(1),@"data":data};
      [[CacheDataHelper shareHelper].cacheTool setObject:tempData forKey:key];
      [[CacheDataHelper shareHelper].keyList addObject:key];
}

- (id)getCacheDataByKey:(NSString *)key{
    
    return [[CacheDataHelper shareHelper].cacheTool objectForKey:key] ;
}
- (void)removeCacheDataByKey:(NSString *)key{
    [[CacheDataHelper shareHelper].cacheTool removeObjectForKey:key];
     [[CacheDataHelper shareHelper].keyList removeObject:key];
}

- (void)updateBtTimeTypeKey:(NSString *)key{
    NSMutableDictionary *data = [[self getCacheDataByKey:key] mutableCopy];
    if(data ){
        NSNumber  *time = [data objectForKey:@"time"];
        time = @(time.integerValue + 1);
        [data setValue:time forKey:@"time"];
        
        [[CacheDataHelper shareHelper].cacheTool setObject:data forKey:key];
    }else{
        NSLog(@"缓存中没有该值");
    }
  
}

- (void)checkData{
    if ([CacheDataHelper shareHelper].keyList.count) {
        [[CacheDataHelper shareHelper].keyList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSMutableDictionary *data = [[[CacheDataHelper shareHelper] getCacheDataByKey:obj] mutableCopy];
      
            NSNumber  *timeO = [data valueForKey:@"time"];
            if ( timeO.integerValue && data) {
                timeO = @(timeO.integerValue - 1);
                [data setValue:timeO forKey:@"time"];
                [[CacheDataHelper shareHelper].cacheTool setObject:data forKey:obj];
            }else{
                [[CacheDataHelper shareHelper] removeCacheDataByKey:obj];
            }
           
        }];
    }

}


@end
